package com.example.homeworktagger.service;

import com.example.homeworktagger.model.Question;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * CSV文件导入服务
 * 
 * 负责解析CSV文件并将其中的题目数据导入系统
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CsvImportService {

    /** 数据导入服务 */
    private final DataImportService dataImportService;

    /**
     * 导入CSV文件
     * 
     * @param file 上传的CSV文件
     * @throws RuntimeException 导入过程中出现错误
     */
    public void importCsvFile(MultipartFile file) {
        try {
            // 1. 解析CSV文件为题目对象列表
            List<Question> questions = parseCsvFile(file);
            
            // 2. 调用数据导入服务，将题目导入Milvus
            dataImportService.importQuestions(questions);
            
            log.info("成功导入 {} 条问题", questions.size());
        } catch (Exception e) {
            log.error("导入CSV文件失败", e);
            throw new RuntimeException("导入CSV文件失败: " + e.getMessage(), e);
        }
    }

    /**
     * 解析CSV文件为题目对象列表
     * 
     * @param file CSV文件
     * @return 题目对象列表
     * @throws IOException CSV文件读取错误
     * @throws CsvValidationException CSV格式错误
     */
    private List<Question> parseCsvFile(MultipartFile file) throws IOException, CsvValidationException {
        List<Question> questions = new ArrayList<>();
        
        try (CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream()))) {
            // 跳过标题行
            reader.readNext();
            
            String[] line;
            while ((line = reader.readNext()) != null) {
                if (line.length >= 2) {
                    Question question = new Question();
                    question.setQuestion(line[0].trim());
                    question.setAnswer(line[1].trim());
                    questions.add(question);
                }
            }
        }
        
        log.debug("从CSV解析了 {} 条题目", questions.size());
        return questions;
    }
} 